<template>
  <div class="container mx-auto px-4 py-8">
    <el-card class="box-card mb-6">
      <template #header>
        <div class="clearfix">
          <span class="text-xl font-bold">销售报表</span>
          <el-button
            v-if="exportLoading"
            type="text"
            disabled
            class="float-right"
          >
            <i class="el-icon-loading"></i> 导出中...
          </el-button>
          <el-button
            v-else
            type="text"
            @click="exportExcel"
            class="float-right"
          >
            <i class="el-icon-download"></i> 导出Excel
          </el-button>
        </div>
      </template>

      <el-form :inline="true" :model="queryParams" class="mb-6">
        <!-- 年份选择器 -->
        <el-form-item label="年份">
          <el-select
            v-model="queryParams.selectedYear"
            placeholder="请选择年份"
            @change="handleDateChange"
          >
            <el-option
              v-for="year in yearOptions"
              :key="year"
              :label="year"
              :value="year"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 月份选择器 -->
        <el-form-item label="月份">
          <el-select
            v-model="queryParams.selectedMonth"
            placeholder="请选择月份"
            @change="handleDateChange"
          >
            <el-option
              v-for="month in monthOptions"
              :key="month"
              :label="`${month}月`"
              :value="month"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="门店">
          <el-input
            v-model="queryParams.storeName"
            placeholder="请输入店铺名称"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="商品">
          <el-input
            v-model="queryParams.ProName"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="订单类型">
          <el-radio-group v-model="queryParams.orderType">
            <el-radio :label="'1'">全部</el-radio>
            <el-radio :label="'外卖'">外卖</el-radio>
            <el-radio :label="'到店'">到店</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="fetchSalesData"
            >查询</el-button
          >
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table
        :data="salesData"
        stripe
        border
        highlight-current-row
        class="mb-6"
        :loading="loading"
        empty-text="暂无数据"
      >
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column
          prop="SalesID"
          label="销售记录ID"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="StoreName"
          label="门店"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="SalesDate"
          label="销售日期"
          width="140"
        ></el-table-column>
        <el-table-column
          prop="ProductName"
          label="产品名称"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="Specification"
          label="规格"
          width="100"
        ></el-table-column>
        <el-table-column prop="UnitPrice" label="单价" width="100">
          <template #default="scope">
            {{ scope.row.UnitPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="Quantity"
          label="数量"
          width="100"
        ></el-table-column>
        <el-table-column prop="SalesAmount" label="销售额" width="120">
          <template #default="scope">
            <span class="text-primary font-medium">{{
              scope.row.SalesAmount.toFixed(2)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="OrderType" label="订单类型" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.OrderType === 'Online' ? 'success' : 'info'"
            >
              {{ scope.row.OrderType === "Online" ? "线上" : "线下" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="Operator"
          label="操作人员"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="CreateTime"
          label="创建时间"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="mini" type="text" @click="viewDetails(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="!loading && salesData.length === 0" class="text-center py-10">
        <el-empty description="暂无符合条件的数据"></el-empty>
      </div>
      
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      ></el-pagination>
    </el-card>

    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
      <el-card class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>总销售额</span>
          <el-tooltip
            class="item"
            effect="dark"
            content="与上周同期相比"
            placement="top"
          >
            <i class="el-icon-question help-icon"></i>
          </el-tooltip>
        </div>
        <div class="text-center py-4">
          <div class="text-4xl font-bold text-gray-900 mb-2">
            ¥{{ totalSalesAmount.toFixed(2) }}
          </div>
          <div class="text-sm text-gray-500">
            <span
              :class="salesGrowthRate >= 0 ? 'text-green-500' : 'text-red-500'"
            >
              <i
                :class="
                  salesGrowthRate >= 0
                    ? 'el-icon-arrow-up'
                    : 'el-icon-arrow-down'
                "
              ></i>
              {{ Math.abs(salesGrowthRate).toFixed(1) }}%
            </span>
            较上周
          </div>
        </div>
      </el-card>

      <el-card class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>订单总数</span>
          <el-tooltip
            class="item"
            effect="dark"
            content="与上周同期相比"
            placement="top"
          >
            <i class="el-icon-question help-icon"></i>
          </el-tooltip>
        </div>
        <div class="text-center py-4">
          <div class="text-4xl font-bold text-gray-900 mb-2">
            {{ totalOrderCount }}
          </div>
          <div class="text-sm text-gray-500">
            <span
              :class="orderGrowthRate >= 0 ? 'text-green-500' : 'text-red-500'"
            >
              <i
                :class="
                  orderGrowthRate >= 0
                    ? 'el-icon-arrow-up'
                    : 'el-icon-arrow-down'
                "
              ></i>
              {{ Math.abs(orderGrowthRate).toFixed(1) }}%
            </span>
            较上周
          </div>
        </div>
      </el-card>

      <el-card class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>客单价</span>
          <el-tooltip
            class="item"
            effect="dark"
            content="与上周同期相比"
            placement="top"
          >
            <i class="el-icon-question help-icon"></i>
          </el-tooltip>
        </div>
        <div class="text-center py-4">
          <div class="text-4xl font-bold text-gray-900 mb-2">
            ¥{{ avgOrderAmount.toFixed(2) }}
          </div>
          <div class="text-sm text-gray-500">
            <span
              :class="avgGrowthRate >= 0 ? 'text-green-500' : 'text-red-500'"
            >
              <i
                :class="
                  avgGrowthRate >= 0 ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
                "
              ></i>
              {{ Math.abs(avgGrowthRate).toFixed(1) }}%
            </span>
            较上周
          </div>
        </div>
      </el-card>
    </div>

    <el-row class="mt-8">
      <el-col :span="24">
        <el-card class="box-card h-full">
          <div slot="header" class="clearfix">
            <span>销售趋势</span>
            <el-radio-group
              v-model="trendType"
              size="small"
              class="float-right"
            >
              <el-radio-button label="day">日</el-radio-button>
              <el-radio-button label="week">周</el-radio-button>
              <el-radio-button label="month">月</el-radio-button>
            </el-radio-group>
          </div>
          <div class="trend-chart" ref="trendChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :visible.sync="dialogVisible" title="销售详情" width="70%">
      <el-card v-if="currentDetail" class="mb-4">
        <div class="flex flex-wrap gap-6">
          <div class="w-full md:w-1/3">
            <p class="text-sm text-gray-500 mb-1">销售记录ID</p>
            <p class="font-medium">{{ currentDetail.SalesID }}</p>
          </div>
          <div class="w-full md:w-1/3">
            <p class="text-sm text-gray-500 mb-1">门店</p>
            <p class="font-medium">{{ currentDetail.StoreName }}</p>
          </div>
          <div class="w-full md:w-1/3">
            <p class="text-sm text-gray-500 mb-1">销售日期</p>
            <p class="font-medium">{{ currentDetail.SalesDate }}</p>
          </div>
          <div class="w-full md:w-1/3">
            <p class="text-sm text-gray-500 mb-1">产品名称</p>
            <p class="font-medium">{{ currentDetail.ProductName }}</p>
          </div>
          <div class="w-full md:w-1/3">
            <p class="text-sm text-gray-500 mb-1">规格</p>
            <p class="font-medium">{{ currentDetail.Specification || "-" }}</p>
          </div>
          <div class="w-full md:w-1/3">
            <p class="text-sm text-gray-500 mb-1">单价</p>
            <p class="font-medium">¥{{ currentDetail.UnitPrice.toFixed(2) }}</p>
          </div>
          <div class="w-full md:w-1/3">
            <p class="text-sm text-gray-500 mb-1">数量</p>
            <p class="font-medium">{{ currentDetail.Quantity }}</p>
          </div>
          <div class="w-full md:w-1/3">
            <p class="text-sm text-gray-500 mb-1">销售额</p>
            <p class="font-medium text-primary">
              ¥{{ currentDetail.SalesAmount.toFixed(2) }}
            </p>
          </div>
          <div class="w-full md:w-1/3">
            <p class="text-sm text-gray-500 mb-1">订单类型</p>
            <el-tag
              :type="currentDetail.OrderType === 'Online' ? 'success' : 'info'"
            >
              {{ currentDetail.OrderType === "Online" ? "线上" : "线下" }}
            </el-tag>
          </div>
          <div class="w-full md:w-1/3">
            <p class="text-sm text-gray-500 mb-1">操作人员</p>
            <p class="font-medium">{{ currentDetail.Operator || "-" }}</p>
          </div>
          <div class="w-full md:w-1/3">
            <p class="text-sm text-gray-500 mb-1">创建时间</p>
            <p class="font-medium">{{ currentDetail.CreateTime }}</p>
          </div>
        </div>
      </el-card>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "SalesReport",
  data() {
    return {
      queryParams: {
        storeName: "",
        ProName: "",
        orderType: "1",
        selectedYear: new Date().getFullYear().toString(),
        selectedMonth: (new Date().getMonth() + 1).toString(),
        salesDate: "",
      },
      yearOptions: this.generateYearOptions(),
      monthOptions: [
        "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"
      ],
      salesData: [],
      stores: [
        { StoreID: 1, StoreName: "旗舰店" },
        { StoreID: 2, StoreName: "科技园店" },
        { StoreID: 3, StoreName: "大学城店" },
        { StoreID: 4, StoreName: "万象城店" },
        { StoreID: 5, StoreName: "西湖店" },
        { StoreID: 6, StoreName: "城东店" },
      ],
      totalCount: 0,
      totalSalesAmount: 0,
      totalOrderCount: 0,
      avgOrderAmount: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      exportLoading: false,
      dialogVisible: false,
      currentDetail: null,
      trendType: "day",
      salesGrowthRate: 12.5,
      orderGrowthRate: 8.2,
      avgGrowthRate: -3.1,
      trendChart: null,
    };
  },
  created() {
    this.handleDateChange();
    this.fetchSalesData();
  },
  mounted() {
    this.fetchSalesData();
    this.initCharts();
  },
  beforeDestroy() {
    if (this.trendChart) this.trendChart.dispose();
  },
  watch: {
    queryParams: {
      handler() {
        this.currentPage = 1;
        this.fetchSalesData();
      },
      deep: true,
    },
    trendType() {
      this.updateTrendChart();
    },
  },
  methods: {
    // 生成年份选项（当前年份前后各5年）
    generateYearOptions() {
      const currentYear = new Date().getFullYear();
      const options = [];
      for (let i = currentYear - 5; i <= currentYear + 5; i++) {
        options.push(i.toString());
      }
      return options;
    },

    // 处理日期选择变化
    handleDateChange() {
      if (this.queryParams.selectedYear && this.queryParams.selectedMonth) {
        this.queryParams.salesDate = `${this.queryParams.selectedYear}-${this.queryParams.selectedMonth.padStart(2, "0")}`;
      }
    },

    // 获取销售数据
    async fetchSalesData() {
      if (!this.queryParams.salesDate) {
        this.$message.warning("请选择年份和月份");
        return;
      }

      this.loading = true;

      try {
        const response = await this.axios.get("HJQ_sales_report", {
          params: {
            page: this.currentPage,
            limit: this.pageSize,
            storeName: this.queryParams.storeName,
            ProductName: this.queryParams.ProName,
            SalesDate: this.queryParams.salesDate,
            orderType: this.queryParams.orderType,
          },
        });

        this.salesData = response.data || [];
        this.totalCount = response.count || 0;
        this.calculateSummary();
        this.updateCharts();
        this.$message.success("数据加载成功");
      } catch (error) {
        console.error("获取销售数据失败", error);
        this.$message.error("数据加载失败，请重试");
      } finally {
        this.loading = false;
      }
    },

    // 重置查询条件
    resetQuery() {
      this.queryParams = {
        storeName: "",
        ProName: "",
        orderType: "1",
        selectedYear: new Date().getFullYear().toString(),
        selectedMonth: (new Date().getMonth() + 1).toString(),
        salesDate: "",
      };
      this.handleDateChange();
      this.currentPage = 1;
    },

    // 分页相关方法
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchSalesData();
    },
    
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchSalesData();
    },

    // 计算汇总数据
    calculateSummary() {
      this.totalSalesAmount = this.salesData.reduce(
        (sum, item) => sum + (item.SalesAmount || 0),
        0
      );
      this.totalOrderCount = this.salesData.length;
      this.avgOrderAmount = this.totalOrderCount > 0 
        ? this.totalSalesAmount / this.totalOrderCount 
        : 0;
    },

    // 查看详情
    viewDetails(row) {
      this.currentDetail = row;
      this.dialogVisible = true;
    },

    // 初始化图表
    initCharts() {
      // 初始化销售趋势图表
      this.trendChart = echarts.init(this.$refs.trendChartRef);
      this.updateTrendChart();

      // 监听窗口大小变化，调整图表尺寸
      window.addEventListener("resize", this.resizeCharts);
    },

    // 调整图表尺寸
    resizeCharts() {
      if (this.trendChart) this.trendChart.resize();
    },

    // 获取周数
    getWeekNumber(date) {
      const d = new Date(+date);
      d.setHours(0, 0, 0, 0);
      d.setDate(d.getDate() + 4 - (d.getDay() || 7));
      const yearStart = new Date(d.getFullYear(), 0, 1);
      return Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
    },

    // 更新销售趋势图表
    updateTrendChart() {
      if (!this.salesData.length) return;
      
      const trendData = this.salesData.reduce((acc, item) => {
        const date = new Date(item.SalesDate);
        const key = this.trendType === 'day' 
          ? this.formatDate(date)
          : this.trendType === 'week' 
            ? `第${this.getWeekNumber(date)}周` 
            : `${date.getFullYear()}-${date.getMonth()+1}`;
        
        acc[key] = (acc[key] || 0) + (item.SalesAmount || 0);
        return acc;
      }, {});
      
      const xAxisData = Object.keys(trendData).sort();
      const seriesData = xAxisData.map(key => trendData[key]);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLabel: {
            rotate: this.trendType === 'day' ? 45 : 0
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '销售额',
          type: 'line',
          data: seriesData,
          smooth: true,
          itemStyle: {
            color: '#409eff'
          }
        }]
      };
      
      this.trendChart.setOption(option);
    },

    // 更新所有图表
    updateCharts() {
      this.updateTrendChart();
    },

    // 格式化日期
    formatDate(date) {
      if (!(date instanceof Date)) {
        date = new Date(date);
      }
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    },

    // 格式化日期时间
    formatDateTime(date) {
      if (!(date instanceof Date)) {
        date = new Date(date);
      }
      return `${this.formatDate(date)} ${date.getHours().toString().padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}:${date.getSeconds().toString().padStart(2, "0")}`;
    },

    // 导出Excel
    async exportExcel() {
      if (!this.queryParams.salesDate) {
        this.$message.warning("请选择年份和月份");
        return;
      }

      this.exportLoading = true;

      try {
        const response = await this.axios.get("HJQ_sales_export", {
          params: {
            salesDate: this.queryParams.salesDate,
            storeName: this.queryParams.storeName,
            ProName: this.queryParams.ProName,
            orderType: this.queryParams.orderType,
          },
          responseType: "blob",
        });

        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.download = `销售报表_${this.formatDate(new Date())}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        this.$message.success("导出成功");
      } catch (error) {
        console.error("导出失败", error);
        this.$message.error("导出失败，请重试");
      } finally {
        this.exportLoading = false;
      }
    },
  },
};
</script>

<style scoped>
.box-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.box-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.text-primary {
  color: #409eff;
}

.help-icon {
  margin-left: 5px;
  cursor: pointer;
}

.trend-chart {
  height: 350px;
  width: 100%;
}
</style>